import threading
from time import sleep
import socket
from StaticClass import FormatData
from StaticClass import Communication
from StaticClass import Code
from hashlib import sha1


class NetworkClient(threading.Thread):
    
    def __init__(self,copier,cliconfig):
        threading.Thread.__init__(self)
        self.copier = copier
        self.cliconfig = cliconfig
        self.stop = False
        self.listelement = []
    
    def run(self):
        print 'client '+self.cliconfig['name']+' launch'
        while self.cliconfig['enable']==True:
            try:
                self.socket = socket.socket ( socket.AF_INET, socket.SOCK_STREAM )
                self.socket.connect((self.cliconfig['ip'], self.cliconfig['port']))
                self.send(FormatData.Str2Data("request",'giveAll'))
                while True:
                    try:
                        data = self.receive()
                        element = FormatData.Data2Str('element', data)
                        if ((element != None) and (element != "")):
                            self.addElement(element)
                            self.rmElement(self.cliconfig['number'])
                    except Exception:
                        break
            except:
                pass
            sleep(5)
    
    def stopConnection(self):
        self.cliconfig['enable']=False
        try:
            self.send(FormatData.Str2Data("quit"))
        except:
            pass
        self.socket = None
    
    def addElement(self,tmpelement):
        add_clipboard = True
        for element in self.listelement:
            if element == tmpelement:
                    add_clipboard = False
        if add_clipboard:
            self.listelement.insert(0,tmpelement)
        
    def rmElement(self,index):
        try:
            del self.listelement[index]
            return True
        except:
            return False
        
    def send(self,data):
        data = FormatData.Str2Data("password",sha1(self.cliconfig['password']).hexdigest())+data
        print 'Clientsend :'+data
        data = FormatData.Str2Data("data", Code.encode(self.cliconfig['password'], data))
        Communication.send(self.socket,data)
    
    def receive(self):
        data = Communication.receive(self.socket)
        data = FormatData.Data2Str('data', data)
        data = Code.decode(self.cliconfig['password'], data)
        return data
    
    def CheckClient(ip,port,password):
        check = False
        try:
            server = ( ip, port )
            
            data = FormatData.Str2Data("password",sha1(password).hexdigest())+FormatData.Str2Data("checkconnection")
            data = FormatData.Str2Data("data", Code.encode(password, data))
            
            tmpsocket = socket.socket ( socket.AF_INET, socket.SOCK_STREAM )
            tmpsocket.settimeout(5)
            tmpsocket.connect(server)
            Communication.send(tmpsocket,data)
            
            data = Communication.receive(tmpsocket)
            data = FormatData.Data2Str('data', data)
            data = Code.decode(password, data)
            if FormatData.Data2Str("checkconnectionok", data) != None:
                check = True
            tmpsocket.close()
        except Exception:
            return False
        if check:
            return True
        return False
    CheckClient = staticmethod(CheckClient)